import { createRouter, createWebHistory, type RouteRecordRaw } from "vue-router";
import { constantRoutes, loginRoute, mainContainerRoute } from "./routers";
import useAuthStore from "@/stores/useAuthStore";
import NProgress from "nprogress"   // 这里报错不影响运行，因为没有定义ts类型
import "nprogress/nprogress.css"
import setting from "@/setting";
import useTabStore from "@/stores/useTabStore";

// 取消进度条右上角加载圆圈
NProgress.configure({ showSpinner: false })

let router = createRouter({
    history: createWebHistory(),
    routes: constantRoutes,
    // 滚动行为
    scrollBehavior() {
        return {
            left: 0,
            top: 0
        }
    }
})

router.beforeEach((to) => {
    NProgress.start()

    const authStore = useAuthStore()

    if (to.path != loginRoute.path && !authStore.authInfo?.token) {
        // 访问的不是登录界面，且未登录，则切换到登录界面
        return loginRoute
    }

    if (to.path != loginRoute.path && !authStore.hasInitRoutes) {
        // 访问的不是登录界面，且已登录，且未初始化路由，则初始化路由
        authStore.initRoutes()
        // 初始化完成后再次重定向到目标路径，继而重新匹配路由，解决界面刷新后找不到路由问题
        return to.path
    }

    if (to.path == loginRoute.path && authStore.authInfo?.token) {
        // 访问的是登录界面，且已登录，则切换到主界面
        return mainContainerRoute
    }

    const route = to.matched.find(route => to.path == route.path)
    if (route) {
        useTabStore().addTab(route)
    }

    return true
})

router.afterEach((to) => {
    document.title = `${setting.platformName} - ${to.meta.title}`
    NProgress.done()
})

export default router